package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: itheima
 * @create: 2022-07-26 12:26
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
    /**
     * 频道条件分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //1.构建分页对象
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        //2.构建查询条件
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        //3.执行查询
        this.page(page, queryWrapper);

        //4.封装响应结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    /**
     * 保存频道
     *
     * @param entity
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel entity) {
        //1.根据名称查询频道是否存在
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, entity.getName());
        int count = this.count(queryWrapper);

        //2.不存在执行新增
        if (count == 0) {
            entity.setIsDefault(false);
            entity.setStatus(false);
            entity.setOrd(1);
            this.save(entity);
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
    }

    @Override
    public ResponseResult listQueue() {
        LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmChannel::getStatus,1);
        wrapper.orderByDesc(WmChannel::getCreatedTime);
        List<WmChannel> list = this.list(wrapper);
        return ResponseResult.okResult(list);
    }
}
